package cn.com.common;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Random;

public class ValidateCode {
	private String codeValue;
	public String getCodeValue() {
		return codeValue;
	}
	public void setCodeValue(String codeValue) {
		this.codeValue = codeValue;
	}
	char[] codeSequence = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
	/**
	 * generate code image
	 * @param height image height
	 * @param width image width
	 * @param charcount generate char count
	 * @return return the image bufferedimage
	 */
	public BufferedImage getValidateCodeImg(int height,int width,int charcount){ //HttpServletRequest request, HttpServletResponse response,
		BufferedImage bufferedImg = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics graphics = bufferedImg.getGraphics();
		graphics.setColor(getRandomColor(100, 250));
		graphics.fillRect(0, 0, width, height);
		int fontSite=height-2;
		graphics.setFont(new Font("Times New Roman", Font.PLAIN, fontSite));
		Random random = new Random();
		graphics.setColor(getRandomColor(160, 200));
		for (int i = 0; i < 25; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			graphics.drawLine(x, y, x + xl, y + yl);			
		}
		StringBuffer randomCode = new StringBuffer();
		int coudeCount=codeSequence.length;
		for (int i = 0; i < charcount; i++) {
			String code = String.valueOf(codeSequence[random.nextInt(coudeCount)]);
			graphics.setColor(getRandomColor(20,140));
			graphics.drawString(code, i * 13 + 6, 16);
			randomCode.append(code);
		}
		setCodeValue(randomCode.toString());  ///set code value
		return bufferedImg;
		
	}
	/**
	 * get random color
	 * @param start
	 * @param end
	 * @return return color
	 */
	private Color getRandomColor(int start, int end) {
		Random random = new Random();
		start=start%255;
		end=end%255;
		int red = start + random.nextInt(end - start);
		int green = start + random.nextInt(end - start);
		int blue = start + random.nextInt(end- start);
		return new Color(red, green, blue);
	}
}
